package custom.security.browser.encoder;

import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 自定义的Md5Encoder
 * Created by wgt on 2017/10/12.
 */
public class Md5PasswordEncoder implements PasswordEncoder {


    @Override
    public String encode(CharSequence charSequence) {
        return encoder(charSequence.toString().getBytes());
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(encoder(charSequence.toString().getBytes()));
    }


    /**
     * 自定义的加密算法
     */
    private static final char[] hexadecimal = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final byte defaultByte = 21;

    private String encoder(byte[] binaryData) {

        if(binaryData.length != 16) {
            byte[] temp = new byte[16];
            for (int i=0;i<temp.length;i++){
                if (binaryData.length<temp.length){
                    if (i<binaryData.length){
                        temp[i] = binaryData[i];
                    }else{
                        temp[i]= defaultByte;
                    }
                }else{
                    temp[i] = binaryData[i];
                }
            }
            binaryData = temp.clone();
        }

        char[] buffer = new char[32];

        for(int i = 0; i < 16; ++i) {
            int low = binaryData[i] & 15;
            int high = (binaryData[i] & 240) >> 4;
            buffer[i * 2] = hexadecimal[high];
            buffer[i * 2 + 1] = hexadecimal[low];
        }
        return new String(buffer);
    }
}
